package cn.android666.badmintonchargecalculator

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.android666.badmintonchargecalculator.databinding.ActivityMainBinding
import cn.android666.badmintonchargecalculator.databinding.AuthorBinding
import java.text.DecimalFormat

@SuppressLint("SetTextI18n")
class MainActivity : AppCompatActivity() {

    private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val decimalFormat: DecimalFormat by lazy { DecimalFormat("0.00") }
    private val spUtil: SPUtil by lazy { SPUtil(this) }
    private val onFocusChangeListener: View.OnFocusChangeListener by lazy {
        View.OnFocusChangeListener { view, hasFocus ->
            calcResult(false)
            if (hasFocus && (view as EditText).text.isNotBlank()) {
                view.setSelection(view.text.length)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.originalSitePriceEdit.onFocusChangeListener = onFocusChangeListener
        binding.siteCouponEdit.onFocusChangeListener = onFocusChangeListener
        binding.bucketBallPriceEdit.onFocusChangeListener = onFocusChangeListener
        binding.useBallCountEdit.onFocusChangeListener = onFocusChangeListener
        binding.ballTotalCostEdit.onFocusChangeListener = onFocusChangeListener
        binding.siteAndBallTotalEdit.onFocusChangeListener = onFocusChangeListener
        binding.boyCountEdit.onFocusChangeListener = onFocusChangeListener
        binding.girlCountEdit.onFocusChangeListener = onFocusChangeListener
        binding.girlDiscountsEdit.onFocusChangeListener = onFocusChangeListener

        binding.calcResultButton.setOnClickListener { calcResult(true) }

        binding.girlDiscountsEdit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                calcResult(true)
                false
            } else {
                false
            }
        }

        // 设置初始值
        binding.originalSitePriceEdit.setText(getString(Keys.originalSitePriceEdit))
        binding.couponSitePriceText.text = getString(Keys.couponSitePriceText)
        binding.siteCouponEdit.setText(getString(Keys.siteCouponEdit))
        binding.bucketBallPriceEdit.setText(getString(Keys.bucketBallPriceEdit))
        binding.oneBallPriceEdit.setText(getString(Keys.oneBallPriceEdit))
        binding.useBallCountEdit.setText(getString(Keys.useBallCountEdit))
        binding.ballTotalCostEdit.setText(getString(Keys.ballTotalCostEdit))
        binding.siteAndBallTotalEdit.setText(getString(Keys.siteAndBallTotalEdit))
        binding.boyCountEdit.setText(getString(Keys.boyCountEdit))
        binding.boyAverageCostText.text = getString(Keys.boyAverageCostText)
        binding.girlCountEdit.setText(getString(Keys.girlCountEdit))
        binding.girlAverageCostText.text = getString(Keys.girlAverageCostText)
        binding.girlDiscountsEdit.setText(getString(Keys.girlDiscountsEdit))
        binding.verifyResultText.text = getString(Keys.verifyResultText)

        // 添加作者
        AuthorBinding.inflate(layoutInflater, findViewById(android.R.id.content), true)
    }

    private fun calcResult(isFromButtonClick: Boolean) {
        // 得到原价场地费和场地优惠券价格
        val originalSitePriceString = binding.originalSitePriceEdit.text.toString()
        val siteCouponString = binding.siteCouponEdit.text.toString()
        val originalSitePrice = if (originalSitePriceString.isBlank()) 0f else originalSitePriceString.toFloat()
        val siteCoupon = if (siteCouponString.isBlank()) 0f else siteCouponString.toFloat()

        // 计算实际场地费用（扣除优惠券）
        val siteCost = if (isBlankOrZero(originalSitePriceString)) 0f else originalSitePrice - siteCoupon
        binding.couponSitePriceText.text = "优惠后价格为：${decimalFormat.format(siteCost)}"

        // 计算平均每个球的价格
        val bucketBallPriceString = binding.bucketBallPriceEdit.text.toString()
        if (bucketBallPriceString.isBlank()) {
            binding.oneBallPriceEdit.setText("")
        } else {
            val bucketBallPrice = bucketBallPriceString.toFloat()
            val oneBallPrice = bucketBallPrice / 12
            binding.oneBallPriceEdit.setText(decimalFormat.format(oneBallPrice))
        }

        // 计算使用球数对应的费用
        val oneBallPriceString = binding.oneBallPriceEdit.text.toString()
        val useBallCountString = binding.useBallCountEdit.text.toString()
        if (!isBlankOrZero(oneBallPriceString) && !isBlankOrZero(useBallCountString)) {
            val oneBallPrice = oneBallPriceString.toFloat()
            val useBallCount = useBallCountString.toInt()
            val ballTotalCost = oneBallPrice * useBallCount
            binding.ballTotalCostEdit.setText(decimalFormat.format(ballTotalCost))
        }

        val ballTotalCostString = binding.ballTotalCostEdit.text.toString()
        val ballTotalCost = if (ballTotalCostString.isBlank()) 0f else ballTotalCostString.toFloat()
        if (siteCost + ballTotalCost > 0) {
            binding.siteAndBallTotalEdit.setText(decimalFormat.format(siteCost + ballTotalCost))
        }

        // 场地费 + 球费 （即可费用）
        if (isEmpty(binding.siteAndBallTotalEdit, "场地费加球费", isFromButtonClick)) {
            return
        }
        val totalCost = binding.siteAndBallTotalEdit.text.toString().toFloat()

        // 男生人数，必须要有男生。如果在实际使用中真的只有女生，则把女生当成男生输入即可。
        if (isEmpty(binding.boyCountEdit, "男生人数", isFromButtonClick)) {
            return
        }
        val boyCount = binding.boyCountEdit.text.toString().toInt()

        // 女生人数，可以为0
        val girlCountString = binding.girlCountEdit.text.toString()
        val girlCount = if (girlCountString.isBlank()) 0 else girlCountString.toInt()

        // 女生优惠 girlDiscountsEdit
        val girlDiscountsString = binding.girlDiscountsEdit.text.toString()
        val girlDiscounts = if (girlDiscountsString.isBlank()) 0f else girlDiscountsString.toFloat()

        // 计算女生平均费用
        val girlAverageCost = if (girlCount == 0) {
            0f
        } else {
            (totalCost - boyCount * girlDiscounts) / (boyCount + girlCount)
        }

        // 计算男生平均费用
        val boyAverageCost = if (girlCount == 0) {
            totalCost / boyCount
        } else {
            girlAverageCost + girlDiscounts
        }

        // 显示结果
        val boyAverageCostString = decimalFormat.format(boyAverageCost)
        val girlAverageCostString = decimalFormat.format(girlAverageCost)
        binding.boyAverageCostText.text = "平均每人费用：$boyAverageCostString"
        binding.girlAverageCostText.text = "平均每人费用：$girlAverageCostString"

        val verifyResult = boyCount * boyAverageCostString.toFloat() + girlCount * girlAverageCostString.toFloat()
        val verifyString = if (girlCount == 0) {
            "验算：$boyCount x $boyAverageCostString = ${decimalFormat.format(verifyResult)}"
        } else {
            "验算：($boyCount x $boyAverageCostString) + ($girlCount x $girlAverageCostString) = ${decimalFormat.format(verifyResult)}"
        }
        binding.verifyResultText.text = verifyString

        // 把各个View的值持久化，在下次打开时自动初始化为上一次的值
        saveTextViewValue(Keys.originalSitePriceEdit, binding.originalSitePriceEdit)
        saveTextViewValue(Keys.couponSitePriceText, binding.couponSitePriceText)
        saveTextViewValue(Keys.siteCouponEdit, binding.siteCouponEdit)
        saveTextViewValue(Keys.bucketBallPriceEdit, binding.bucketBallPriceEdit)
        saveTextViewValue(Keys.oneBallPriceEdit, binding.oneBallPriceEdit)
        saveTextViewValue(Keys.useBallCountEdit, binding.useBallCountEdit)
        saveTextViewValue(Keys.ballTotalCostEdit, binding.ballTotalCostEdit)
        saveTextViewValue(Keys.siteAndBallTotalEdit, binding.siteAndBallTotalEdit)
        saveTextViewValue(Keys.boyCountEdit, binding.boyCountEdit)
        saveTextViewValue(Keys.boyAverageCostText, binding.boyAverageCostText)
        saveTextViewValue(Keys.girlCountEdit, binding.girlCountEdit)
        saveTextViewValue(Keys.girlAverageCostText, binding.girlAverageCostText)
        saveTextViewValue(Keys.girlDiscountsEdit, binding.girlDiscountsEdit)
        saveTextViewValue(Keys.verifyResultText, binding.verifyResultText)
    }

    private fun isEmpty(editText: EditText, name: String, isFromButtonClick: Boolean): Boolean {
        val string = editText.text.toString()
        return if (string.isBlank() || string.toFloat() < 1f) { // 如果输入的数值小于1，也认为是空的。
            if (isFromButtonClick) {
                Toast.makeText(this, "请输入$name", Toast.LENGTH_SHORT).apply { setGravity(Gravity.CENTER, 0, 0) }.show()
            }
            true
        } else {
            false
        }
    }

    private fun saveTextViewValue(key: String, textView: TextView) = spUtil.putString(key, textView.text.toString())
    private fun getString(key: String) = spUtil.getString(key)
    private fun isBlankOrZero(string: String) = string.isBlank() || string == "0" || string == "0.00"
}